import axios, { AxiosInstance, AxiosResponse } from 'axios';
import toast from 'react-hot-toast';
import type {
  ApiResponse,
  LoginRequest,
  RegisterRequest,
  SendSmsRequest,
  AuthResponse,
  InterestTag,
  RecommendationUser,
  SwipeRequest,
  SwipeResponse,
  Match,
  MatchDetail,
  ChatMessage,
  SendMessageRequest,
  Notification,
  SoulQuestion,
  SoulMatch,
  UpdateLocationRequest,
  NearbyUser,
  GetNearbyUsersRequest,
  GetUserLocationRequest
} from '../types/api';

class ApiService {
  private api: AxiosInstance;

  constructor() {
    this.api = axios.create({
      baseURL: '/api',
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // 请求拦截器
    this.api.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token');
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.api.interceptors.response.use(
      (response: AxiosResponse<ApiResponse>) => {
        if (response.data.code !== 0) {
          toast.error(response.data.msg || '请求失败');
          return Promise.reject(new Error(response.data.msg));
        }
        return response;
      },
      (error) => {
        const message = error.response?.data?.msg || error.message || '网络错误';
        toast.error(message);
        return Promise.reject(error);
      }
    );
  }

  // 认证相关
  async sendSms(data: SendSmsRequest): Promise<ApiResponse> {
    const response = await this.api.post('/user/send-sms', data);
    return response.data;
  }

  async register(data: RegisterRequest): Promise<ApiResponse<{ user_id: number }>> {
    const response = await this.api.post('/user/register', data);
    return response.data;
  }

  async login(data: LoginRequest): Promise<ApiResponse<AuthResponse>> {
    const response = await this.api.post('/user/login', data);
    return response.data;
  }

  // 兴趣标签
  async getInterestTags(): Promise<ApiResponse<{ tags: InterestTag[] }>> {
    const response = await this.api.get('/user/interestTags');
    return response.data;
  }

  async saveUserInterests(data: { user_id: number; tag_ids: number[] }): Promise<ApiResponse> {
    const response = await this.api.post('/user/interests/save', data);
    return response.data;
  }

  // 推荐和滑动
  async getRecommendations(userId: number, page = 1, pageSize = 10): Promise<ApiResponse<{ users: RecommendationUser[]; total: number }>> {
    const response = await this.api.get('/user/recommendations', {
      params: { user_id: userId, page, page_size: pageSize }
    });
    return response.data;
  }

  async getSmartRecommendations(userId: number, limit = 10): Promise<ApiResponse<{ users: RecommendationUser[] }>> {
    const response = await this.api.get('/user/smart-recommendations', {
      params: { user_id: userId, limit }
    });
    return response.data;
  }

  async swipeUser(data: SwipeRequest): Promise<ApiResponse<SwipeResponse>> {
    const response = await this.api.post('/user/swipe', data);
    return response.data;
  }

  // 匹配
  async getMatches(userId: number, page = 1, pageSize = 10): Promise<ApiResponse<{ matches: Match[]; total: number }>> {
    const response = await this.api.get('/user/matches', {
      params: { user_id: userId, page, page_size: pageSize }
    });
    return response.data;
  }

  async getMatchDetail(userId: number, matchId: number): Promise<ApiResponse<MatchDetail>> {
    const response = await this.api.get('/user/match/detail', {
      params: { user_id: userId, match_id: matchId }
    });
    return response.data;
  }

  // 聊天
  async sendMessage(data: SendMessageRequest): Promise<ApiResponse<{ message_id: number }>> {
    const response = await this.api.post('/user/message/send', data);
    return response.data;
  }

  async getChatMessages(userId: number, matchId: number, page = 1, pageSize = 20): Promise<ApiResponse<{ messages: ChatMessage[]; total: number }>> {
    const response = await this.api.get('/user/messages', {
      params: { user_id: userId, match_id: matchId, page, page_size: pageSize }
    });
    return response.data;
  }

  async markMessagesAsRead(userId: number, matchId: number): Promise<ApiResponse> {
    const response = await this.api.post('/user/messages/read', {
      user_id: userId,
      match_id: matchId
    });
    return response.data;
  }

  async getUnreadMessageCount(userId: number): Promise<ApiResponse<{ count: number }>> {
    const response = await this.api.get('/user/messages/unreadCount', {
      params: { user_id: userId }
    });
    return response.data;
  }

  // 通知
  async getNotifications(userId: number, page = 1, pageSize = 10): Promise<ApiResponse<{ notifications: Notification[]; total: number }>> {
    const response = await this.api.get('/user/notifications', {
      params: { user_id: userId, page, page_size: pageSize }
    });
    return response.data;
  }

  async markNotificationAsRead(userId: number, notificationId: number): Promise<ApiResponse> {
    const response = await this.api.post('/user/notification/read', {
      user_id: userId,
      notification_id: notificationId
    });
    return response.data;
  }

  // 灵魂匹配
  async getSoulQuestions(userId: number, category = '', limit = 10): Promise<ApiResponse<{ questions: SoulQuestion[] }>> {
    const response = await this.api.get('/user/soul/questions', {
      params: { user_id: userId, category, limit }
    });
    return response.data;
  }

  async submitSoulAnswer(data: { user_id: number; question_id: number; answers: string[]; answer_score: number }): Promise<ApiResponse> {
    const response = await this.api.post('/user/soul/answer', data);
    return response.data;
  }

  async getSoulMatches(userId: number, page = 1, pageSize = 10): Promise<ApiResponse<{ matches: SoulMatch[]; total: number }>> {
    const response = await this.api.get('/user/soul/matches', {
      params: { user_id: userId, page, page_size: pageSize }
    });
    return response.data;
  }

  async getSoulMatchDetail(userId: number, targetUserId: number): Promise<ApiResponse<SoulMatch>> {
    const response = await this.api.get('/user/soul/match/detail', {
      params: { user_id: userId, target_user_id: targetUserId }
    });
    return response.data;
  }

  // LBS功能
  async updateLocation(data: UpdateLocationRequest): Promise<ApiResponse> {
    const response = await this.api.post('/user/location/update', data);
    return response.data;
  }

  async getNearbyUsers(data: GetNearbyUsersRequest): Promise<ApiResponse<{ users: NearbyUser[] }>> {
    const response = await this.api.post('/user/nearby/users', data);
    return response.data;
  }

  async getUserLocation(data: GetUserLocationRequest): Promise<ApiResponse<Location>> {
    const response = await this.api.post('/user/location/get', data);
    return response.data;
  }

  // 好友系统
  async addFriend(data: { user_id: number; target_user_id: number; group_id?: number; remark?: string }): Promise<ApiResponse> {
    const response = await this.api.post('/user/friend/add', data);
    return response.data;
  }

  async removeFriend(data: { user_id: number; target_user_id: number }): Promise<ApiResponse> {
    const response = await this.api.post('/user/friend/remove', data);
    return response.data;
  }

  async getFriends(userId: number): Promise<ApiResponse<{ groups: any[] }>> {
    const response = await this.api.get('/user/friends', { params: { user_id: userId } });
    return response.data;
  }

  async createFriendGroup(data: { user_id: number; group_name: string }): Promise<ApiResponse<{ group_id: number }>> {
    const response = await this.api.post('/user/friend/group/create', data);
    return response.data;
  }

  async renameFriendGroup(data: { user_id: number; group_id: number; group_name: string }): Promise<ApiResponse> {
    const response = await this.api.post('/user/friend/group/rename', data);
    return response.data;
  }

  async deleteFriendGroup(data: { user_id: number; group_id: number }): Promise<ApiResponse> {
    const response = await this.api.post('/user/friend/group/delete', data);
    return response.data;
  }

  async moveFriendToGroup(data: { user_id: number; target_user_id: number; to_group_id: number }): Promise<ApiResponse> {
    const response = await this.api.post('/user/friend/moveToGroup', data);
    return response.data;
  }

  // 好友动态
  async postFriendActivity(data: { user_id: number; content: string; images?: string[] }): Promise<ApiResponse<{ activity_id: number }>> {
    const response = await this.api.post('/user/friend/activity/post', data);
    return response.data;
  }

  async getFriendActivities(userId: number, page = 1, pageSize = 20): Promise<ApiResponse<{ activities: any[]; total: number }>> {
    const response = await this.api.get('/user/friend/activities', {
      params: { user_id: userId, page, page_size: pageSize }
    });
    return response.data;
  }
}

export const apiService = new ApiService();
